package com.msb.juc.c_020;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Phaser按照不同的阶段来执行
 * 写遗传算法时可以使用
 */
public class T08_Phaser {

    static Random r = new Random();
    static Phaser phaser = new MarrigePhaser();

    static void miliSleep(int milli) {
        try {
            TimeUnit.MILLISECONDS.sleep(milli);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        phaser.bulkRegister(5);
        for (int i = 0; i < 5; i++) {
            final int nameIndex = i;
            new Thread(() -> {
                Person p = new Person("person" + nameIndex);
                p.arrive();
                phaser.arriveAndAwaitAdvance();
                p.eat();
                phaser.arriveAndAwaitAdvance();
                p.leave();
                phaser.arriveAndAwaitAdvance();
            }).start();
        }
    }

    static class MarrigePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("所有人都到齐了");
                    return false;
                case 1:
                    System.out.println("所有人都吃完了");
                    return false;
                case 2:
                    System.out.println("所有人离开了");
                    System.out.println("婚礼结束");
                    return true;
                default:
                    return true;
            }
        }
    }

    static class Person {
        String name;

        public Person(String name) {
            this.name = name;
        }

        public void arrive() {
            miliSleep(r.nextInt(1000));
            System.out.printf("%s 到达现场~\n", name);
        }

        public void eat() {
            miliSleep(r.nextInt(1000));
            System.out.printf("%s 吃完~\n", name);
        }

        public void leave() {
            miliSleep(r.nextInt(1000));
            System.out.printf("%s 离开~\n", name);
        }
    }
}


